<?php
/**
 * fly
 * Copyright By 5920Team (http://www.5920.me)
 * User: yu@5920.me
 * Date: 13-9-29
 * Time: 下午2:36
 */


class MysqliDbAdapter extends DbAdapter
{
    /**
     * @var mysqli
     */
    public $link;

    /**
     * @return bool|MysqliDbAdapter
     */
    static public function run()
    {
        if(function_exists('mysqli_connect'))
        {
            return new MysqliDbAdapter;
        }else{
            return false;
        }
    }

    /**
     * @param $host
     * @param $username
     * @param $password
     * @param $database
     * @param string $charset
     * @param bool $pConnect
     */
    public function connect($host, $username, $password, $database, $charset = "utf8", $pConnect = false){
        $host = $pConnect ? 'p:' . $host : $host;
        $this->link = new mysqli($host, $username, $password);
        if ($this->error())
        {
            exit('Connect Error' . $this->error());
        }
        $this->query('set names ' . $charset);
        $this->query('use ' . $database);
    }

    /**
     * @param $query
     * @return bool|mysqli_result
     */
    public function query($query){
        return $this->link->query($query);
    }

    /**
     * @param $result mysqli_result
     */
    public function fetchAssoc($result){
       return $result->fetch_assoc();
    }

    /**
     * @return mixed
     */
    public function insertId(){
        return $this->link->insert_id;
    }

    /**
     * @return int
     */
    public function affectedRows(){
        return $this->link->affected_rows;
    }


    /**
     * @param $result mysqli_result
     */
    public function freeResult($result){
        return $result->close();
    }

    /**
     * @return bool
     */
    public function close(){
        return $this->link->close();
    }

    /**
     * @return string
     */
    public function error(){
        return  $this->link->connect_errno . $this->link->connect_error;
    }
}